package com.gy.yemall.yemallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gy.common.constant.ProductConstant;
import com.gy.yemall.yemallproduct.dao.AttrAttrgroupRelationDao;
import com.gy.yemall.yemallproduct.dao.AttrGroupDao;
import com.gy.yemall.yemallproduct.dao.CategoryDao;
import com.gy.yemall.yemallproduct.entity.AttrAttrgroupRelationEntity;
import com.gy.yemall.yemallproduct.entity.AttrGroupEntity;
import com.gy.yemall.yemallproduct.entity.CategoryEntity;
import com.gy.yemall.yemallproduct.entity.vo.AttrAtrrGroupRelationVo;
import com.gy.yemall.yemallproduct.entity.vo.AttrVo;
import com.gy.yemall.yemallproduct.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.common.utils.PageUtils;
import com.gy.common.utils.Query;

import com.gy.yemall.yemallproduct.dao.AttrDao;
import com.gy.yemall.yemallproduct.entity.AttrEntity;
import com.gy.yemall.yemallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAndRelation(AttrAtrrGroupRelationVo attrAtrrGroupRelationVo) {
        AttrEntity attrEntity = new AttrEntity();
        // 拷贝属性
        BeanUtils.copyProperties(attrAtrrGroupRelationVo, attrEntity);
        // 下面的attrEntity可以复用
        this.save(attrEntity);

        if (attrAtrrGroupRelationVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 对关联表进行修改
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrAtrrGroupRelationVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils show(Map<String, Object> params, Long catId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type",
                        "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (catId != 0) {
            wrapper.eq("catelog_id", catId);
        }

        if (!StringUtils.isEmpty(key)) {
            wrapper.and((wrap) -> {
                wrap.eq("attr_id", key).or().eq("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        // 获取查询出来的所有的属性实体
        List<AttrEntity> records = page.getRecords();
        // 取出每一个实体的attr_id
        List<AttrVo> respList = records.stream().map((attrEntity) -> {
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(attrEntity, attrVo);
            // 基础属性才需要进行分组，销售属性不需要
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrVo.setCatelogName(categoryEntity.getName());
            }
            return attrVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respList);
        return pageUtils;
    }

    @Override
    public AttrVo getInfoBy(Long attrId) {

        AttrVo attrVo = new AttrVo();
        // 查询属性表
        AttrEntity attrEntity = attrDao.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrVo);

        // 只有基础属性才会进行更新关联表
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if (attr_id != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                // 给Vo设置属性
                attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                attrVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }



        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        // 查询CatelogPath
        Long[] catelogPath = categoryService.getCatelogPathById(categoryEntity.getCatId());

        // 给Vo设置属性
        attrVo.setCatelogName(categoryEntity.getName());
        attrVo.setCatelogPath(catelogPath);

        System.out.println("=============" + attrVo);
        return attrVo;
    }

    @Transactional
    @Override
    public void updateDetail(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        // 更新属性表本身
        attrDao.updateById(attrEntity);

        // 最新的 attrGroupId, 更新关系表
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        relationEntity.setAttrId(attrVo.getAttrId());

        // 防止原本attr_id没有对应分组，该方法判断符合这个条件的所有记录
        Integer count = attrAttrgroupRelationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id", attrVo.getAttrId()));
        if (count > 0) {
            // 说明我们是做修改操作
            attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrVo.getAttrId()));
        } else {
            // 做新增操作
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    @Override
    public List<Long> queryByAttrIds(List<Long> attrIds) {
        List<Long> longs = attrDao.queryByAttrIds(attrIds);
        return longs;
    }


}